/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import io.renren.cloud.OSSFactory;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Result;
import io.renren.entity.SysOssEntity;
import io.renren.service.SysOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 文件上传
 * 
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("canteens/oss")
@Api(tags="通用接口")
public class SysOssController {
	@Autowired
	private SysOssService sysOssService;


    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;

	@PostMapping("upload")
	@ApiOperation(value = "上传文件")
	public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			return new Result<Map<String, Object>>().error(ErrorCode.UPLOAD_FILE_EMPTY);
		}
		//上传文件
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		String url = OSSFactory.build().uploadSuffix(file.getBytes(), extension);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.insert(ossEntity);
		Map<String, Object> data = new HashMap<>(1);
		data.put("src", url);
		return new Result<Map<String, Object>>().ok(data);
	}




	@PostMapping("/uploads")
	public Result<Map<String, Object>> upload(HttpServletRequest request) throws Exception {
		if (!(request instanceof StandardMultipartHttpServletRequest)) {
			throw new RRException("上传文件不能为空");
		}
		Collection<MultipartFile> values = ((StandardMultipartHttpServletRequest) request).getFileMap().values();
		String  projectId =request.getParameter("projectId");
		List<String> urls = new ArrayList<>(values.size());
		for (MultipartFile file : values) {
			//上传文件
			String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
			String url = sysOssService.upload(file.getBytes(), suffix,projectId);
			urls.add(url);
		}
		Map<String, Object> data = new HashMap<>(1);
		data.put("urls", urls);
		return new Result<Map<String, Object>>().ok(data);
	}




}